'''
Created on 2021年1月15日

@author: Administrator
'''
from flask import json
from peewee import JOIN, fn

from common.public import *
from orm.model import db, CompanyDetails, Company, User, Dept
from view.baseview import BaseView


class InnerWorkOrderView(BaseView):

    def __init__(self):
        pass
  
    def queryInnerWorkOrder(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        result = []
        where_condition = True
        queryFlag = False
        where_details_condition = True
        total = 0
        print(params)
        if params["keyword"]:
            likestr = "%" + params["keyword"] + "%"
            where_condition = (Company.title ** likestr)
            where_condition = where_condition | (Company.remake ** likestr)

        if params["name"]:
            where_condition = where_condition & (Company.title == params["name"])
        if params["endTime"]:
            where_condition = where_condition & ((Company.enddate >= params["endTime"][0] + " 00:00:00") \
                                               & (Company.enddate <= params["endTime"][1] + " 23:59:59"))
        if params["createTime"]:
            where_condition = where_condition & ((Company.create_time >= params["createTime"][0] + " 00:00:00") \
                                               & (Company.create_time <= params["createTime"][1] + " 23:59:59"))
        if params["updateTime"]:
            where_condition = where_condition & ((Company.update_time >= params["updateTime"][0] + " 00:00:00") \
                                               & (Company.update_time <= params["updateTime"][1] + " 23:59:59"))
        if params['charger']:
            where_condition = where_condition & (Company.leader_id.in_(params['charger']))
        if params["status"]:
            where_details_condition = where_details_condition & (CompanyDetails.status == params["status"])
            queryFlag = True
        if params["matter"]:
            where_details_condition = where_details_condition & (CompanyDetails.matter == params["matter"])
            queryFlag = True
        # 取得部门管辖区域
        if params["userid"]:
            user = User.get(User.id == params["userid"])
            # 取得部门列表ID
            deptids = Dept.select(Dept.id).where(Dept.up_id==user.dept_id)
            if deptids:
                # 如果取到部门列表，说明是总经办部门人员
                pass
            else:
                # 如果取不到部门列表，说明是总经办部门以外人员
                leader = User.select().where(User.id==params["userid"]).first()
                ids = []
                if leader.isleader == COMMON_TRUE:
                    # 如果是主管
                    rows = User.select(User.id).where(User.leader_id==params["userid"])
                    for row in rows:
                        ids.append(row.id)
                    ids.append(params["userid"])
                else:
                    ids.append(params["userid"])
                where_condition = where_condition & (Company.leader_id.in_(ids) | Company.audit_leader_id.in_(ids) | Company.applicant_id.in_(ids)) 
                
        rows = Company.select().where(where_condition).order_by(Company.create_time.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        total = rows.count()
        displaynumber = 0
        for row in rows:
            if row.create_time != None:
                row.create_time = time.strftime("%Y-%m-%d", time.strptime(str(row.create_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            if row.enddate != None:
                row.enddate = time.strftime("%Y-%m-%d", time.strptime(str(row.enddate), "%Y-%m-%d"))
             
            companydetailrows = CompanyDetails.select().where((CompanyDetails.company_id == row.id) & (where_details_condition))
  
            if queryFlag:
                if not companydetailrows:
                    displaynumber += 1
                    continue
            companydetailrows = CompanyDetails.select().where(CompanyDetails.company_id == row.id)
            recs = []
            for companydetailrow in companydetailrows:
                if companydetailrow.create_time != None:
                    companydetailrow.create_time = time.strftime("%Y-%m-%d", time.strptime(str(companydetailrow.create_time), "%Y-%m-%d %H:%M:%S"))
                if companydetailrow.update_time != None:
                    companydetailrow.update_time = time.strftime("%Y-%m-%d", time.strptime(str(companydetailrow.update_time), "%Y-%m-%d %H:%M:%S"))
                if companydetailrow.end_time != None:
                    companydetailrow.end_time = time.strftime("%Y-%m-%d", time.strptime(str(companydetailrow.end_time), "%Y-%m-%d"))
                recs.append({"id":companydetailrow.id,
                 "innerworkorderId":companydetailrow.company_id,
                 "chargerId":companydetailrow.charger_id,
                 "charger":companydetailrow.charger.username,
                 "matter":companydetailrow.matter,
                 "status":companydetailrow.status,
                "remake":companydetailrow.remake,
                "evidence":json.loads(companydetailrow.evidence),
                "endTime":companydetailrow.end_time,
                "updateTime":companydetailrow.update_time,
                "createTime":companydetailrow.create_time
                             })
            if recs.__len__() == 0:
                recs = []

            newmatter = ""
            newstatus = ""
            udate = ""
            updatefirstrow = CompanyDetails.select().where(CompanyDetails.company_id == row.id).order_by(CompanyDetails.update_time.desc()).first()
            if updatefirstrow != None:
                newmatter = updatefirstrow.matter
                newstatus = updatefirstrow.status
                udate = time.strftime("%Y-%m-%d", time.strptime(str(updatefirstrow.update_time), "%Y-%m-%d %H:%M:%S"))
            data = {
                "id":row.id,
                "leader":row.leader.username + "[" + row.leader_status + "]",
                "leaderId":row.leader.id,
                "auditleader":row.audit_leader.username + "[" + row.audit_leader_status + "]",
                "applicantId":row.applicant_id,
                "applicant":row.applicant.username,
                "auditleaderId":row.audit_leader.id,
                "auditleaderStatus":row.audit_leader_status,
                "leaderStatus":row.leader_status,
                "auditStatus":row.status,
                "matter":newmatter,
                "status":newstatus,
                "name":row.title,
                "remake":row.remake,
                "createTime":row.create_time,
                "updateTime":udate,
                "enddate":row.enddate,
                "evidence":json.loads(row.evidence),
                "recs":recs
               
             }
            result.append(data)
        total = total - displaynumber
        return super().resultSet(200, "", result, total)

    @db.atomic()                   
    def distributeInnerWorkOrder(self, params):
        """
        更新
        """
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        # 更新负责人期限
        company = Company.get(Company.id == params["id"])
        company.enddate = params["enddate"]
        company.leader_id = params["leaderId"]
        company.remake = params["remake"]
        company.evidence = params["evidence"]
        company.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        company.audit_leader_status = AUDIT_STATUS_WAITE
        company.leader_status = AUDIT_STATUS_WAITE

        company.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    @db.atomic()                   
    def addInnerWorkOrder(self, params):
        """
                        新增
        """
        # 新增内部工单
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        print(params)
        Company.create(
            remake = params["remake"],
            title = params["name"],
            leader_id = params["leaderId"],
            applicant_id = params["applicantId"],
            audit_leader_id = params["auditleaderId"],
            enddate = params["enddate"],
            evidence = params["evidence"],
            leader_status = AUDIT_STATUS_WAITE,
            audit_leader_status = AUDIT_STATUS_WAITE,
            status = AUDIT_STATUS_WAITE,
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def addInnerWorkOrderItem(self, params):
        """
      新增item
        """
        print(params)
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        CompanyDetails.create(
            company_id = params["innerworkorderId"],
            charger_id = params["chargerId"],
            matter = params["matter"],
            status = params["status"],
            remake = params["remake"],
            evidence = params["evidence"],
            end_time = params["endTime"],
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")

    @db.atomic()                   
    def editInnerWorkOrderItem(self, params):
        """
      修改
        """
        print(params)
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        companydetail = CompanyDetails.get(CompanyDetails.id == params["id"])
        companydetail.status = params["status"]
        companydetail.end_time = params["endTime"]
        companydetail.charger_id = params["chargerId"]
        companydetail.matter = params["matter"]
        companydetail.remake = params["remake"]
        companydetail.evidence = params["evidence"]
        companydetail.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        companydetail.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def removeInnerWorkOrderItem(self, params):
        """
      删除详情
        """
        print(params)
        companydetail = CompanyDetails.get(CompanyDetails.id == params["id"])
        companydetail.delete_instance()
        return super().resultSet(200, "删除成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def removeMulInnerWorkOrder(self, params):
        """
      多选删除
        """
        print(params["ids"])
        CompanyDetails.delete().where(CompanyDetails.company_id.in_(params["ids"])).execute()
        Company.delete().where(Company.id.in_(params["ids"])).execute()
        return super().resultSet(200, "删除成功", [])
        raise Exception("更新失败")

    @db.atomic() 
    def audit(self, params):
        print(params)
        company = Company.get(Company.id == params["id"])
        if int(params["userid"]) == params["auditleaderId"] and company.audit_leader_status == AUDIT_STATUS_WAITE:
            # 发起者部长审核
            company.audit_leader_status=AUDIT_STATUS_PASSED
            company.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        elif int(params["userid"]) == params["leaderId"] and company.leader_status == AUDIT_STATUS_WAITE:
            # 协助部门主管
            if company.audit_leader_status==AUDIT_STATUS_PASSED:
                # 如果发起者部长已审核
                company.leader_status=AUDIT_STATUS_PASSED
            else:
                # 如果发起者部长未审核
                return super().resultSet(201, "发起者部长还未审核通过,您无法操作。", [])
        if  company.audit_leader_status == AUDIT_STATUS_PASSED \
            and company.leader_status == AUDIT_STATUS_PASSED:
            # 如果发起者部长，协助部门主管都审核通过，状态改为已审核
            company.status = AUDIT_STATUS_PASSED
        company.save()
        return super().resultSet(200, "审核通过", [])
        raise Exception("审核失败")

    @db.atomic() 
    def nopass(self, params):
        print(params)
        message = ""
        company = Company.get(Company.id == params["id"])
        if int(params["userid"]) == params["auditleaderId"] and company.audit_leader_status == AUDIT_STATUS_WAITE:
            # 发起者部长驳回
            company.audit_leader_status = AUDIT_STATUS_CANCLE
            company.status = AUDIT_STATUS_CANCLE
            company.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        elif int(params["userid"]) == params["leaderId"] and company.leader_status == AUDIT_STATUS_WAITE:
            # 协助部门主管驳回
            if company.audit_leader_status == AUDIT_STATUS_PASSED:
                # 如果发起者部长已审核
                company.leader_status = AUDIT_STATUS_PASSED
                message = "已驳回给主管重新审核。"
            else:
                # 如果发起者部长未审核
                return super().resultSet(201, "发起者部长还未审核通过,您无法操作。", [])

        company.save()
        return super().resultSet(200, message, [])
        raise Exception("驳回失败")
